<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import { StashArrowReply } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTooltip,
} from 'element-plus';

import {
  getChannelSaleDetailApi,
  getSalesChannelApi,
  getSuppliersListApi,
} from '#/api';
import CollapsibleCard from '#/components/collapsibleCard.vue';
import CurrentDateTime from '#/components/currentDateTime.vue';
import { getCommonShortcuts } from '#/utils';

const { locale } = useI18n();
const shortcuts = ref(getCommonShortcuts());

watch(locale, () => {
  shortcuts.value = getCommonShortcuts();
});
const submitForm: any = reactive({
  timeRange: [], // 统计日期
  supplier: [], // 供应商
  salesChannel: [], // 销售渠道
  salesType: '全部', // 销售类型
  publisherName: '', // 供应商
  pageNo: 1, // 页码
  pageSize: 20, // 每页条数
});

const lastCollectDate = ref<any>(null);

const allData = ref<any[]>([]);
const tableData = ref<any[]>([]);

const updateTableData = () => {
  const start = (submitForm.pageNo - 1) * submitForm.pageSize;
  const end = start + submitForm.pageSize;
  tableData.value = allData.value.slice(start, end);
};

const searchLoading = ref(false);
const onSubmit = async () => {
  try {
    searchLoading.value = true;
    const params = {
      startDate: submitForm.timeRange[0],
      endDate: submitForm.timeRange[1],
      publishernames: submitForm.supplier,
      channelnames: submitForm.salesChannel,
      saletype: submitForm.salesType === '全部' ? '' : submitForm.salesType,
      channelname: submitForm.publisherName,
    };
    const { data, systemLastDate } = await getChannelSaleDetailApi(params);
    lastCollectDate.value = systemLastDate;

    data.forEach((item: any) => {
      item.saleDiscount =
        Math.floor((+item.saleShiyang / +item.saleMayang) * 10_000) / 100;
      item.purchaseDiscount =
        Math.floor((+item.pubCostMoney / +item.saleMayang) * 10_000) / 100;
      // 开单毛利 = 实洋 - 进货成本 - 快递 - 平台扣点
      item.saleGrossProfit =
        item.saleShiyang -
        item.pubCostMoney -
        item.expressMoney -
        item.platformMoney;
      // 结算毛利 = 实洋 - 预估成本 - 快递 - 平台扣点
      item.saleSettlementProfit =
        item.saleShiyang -
        item.pubSettMoney -
        item.expressMoney -
        item.platformMoney;
      item.saleGrossProfitMargin =
        Math.floor(
          (+item.saleGrossProfit / Number(item.saleShiyang)) * 10_000,
        ) / 100;
      item.settlementGrossProfitMargin =
        Math.floor(
          (+item.saleSettlementProfit / Number(item.saleShiyang)) * 10_000,
        ) / 100;
    });
    const nfArr = new Set([
      'barCode',
      'bookName',
      'saleGrossProfitMargin',
      'saleNum',
      'serialNo',
    ]);
    data.forEach((item: any) => {
      for (const key in item) {
        if (!nfArr.has(key)) {
          item[key] =
            String(item[key]) === 'infinity' || item[key] === 'NaN'
              ? '-'
              : item?.[key]?.toFixed(2) || '-';
        }
      }
    });
    allData.value = data;
    total.value = data.length;
    submitForm.pageNo = 1;
    updateTableData();
  } catch (error) {
    console.error(error);
  } finally {
    searchLoading.value = false;
  }
};

const total = ref(0);

const handleSizeChange = (val: number) => {
  submitForm.pageSize = val;
  submitForm.pageNo = 1;
  updateTableData();
};
const handleCurrentChange = (val: number) => {
  submitForm.pageNo = val;
  updateTableData();
};

const router = useRouter();
const route = useRoute();

onMounted(() => {
  const kRaw = route.query.k;
  if (!kRaw) {
    router.push('/404');
    return;
  }
  dealUrlParams(kRaw);
  getSupplierType();
  getSalesChannelType();
  onSubmit();
});

const dealUrlParams = (params: any) => {
  const p = JSON.parse(params);
  submitForm.timeRange = p.timeRange;
  submitForm.supplierType = p.supplierType;
  submitForm.salesType = p.salesType;
  submitForm.supplier = p.supplier;
  submitForm.salesChannel = p.salesChannel;
  submitForm.publisherName = p.publisherName;
  submitForm.pageNo = p.pageNo;
  submitForm.pageSize = p.pageSize;
};

const getSupplierType = async () => {
  const { data } = await getSuppliersListApi();
  options.supplierOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};
const getSalesChannelType = async () => {
  const { data } = await getSalesChannelApi();
  options.salesChannelOptions = data.map((item: any) => ({
    label: item,
    value: item,
  }));
};

const options = reactive<any>({
  supplierOptions: [],
  salesChannelOptions: [],
  salesTypeOptions: [
    {
      label: '全部',
      value: '全部',
    },
    {
      label: '经销',
      value: '经销',
    },
    {
      label: '分销',
      value: '分销',
    },
  ],
});

const sortBy = ref('');
const sortOrder = ref('');
const handleSortChange = ({ prop, order }: { order: string; prop: string }) => {
  sortBy.value = prop;
  sortOrder.value = order;
  if (!order) return;
  const notNumber = new Set(['barCode', 'bookName', 'serialNo']);
  allData.value.sort((a: any, b: any) => {
    const aVal = a[prop];
    const bVal = b[prop];
    if (notNumber.has(prop)) {
      return order === 'ascending'
        ? String(aVal).localeCompare(String(bVal))
        : String(bVal).localeCompare(String(aVal));
    } else {
      return order === 'ascending'
        ? Number(aVal) - Number(bVal)
        : Number(bVal) - Number(aVal);
    }
  });
  updateTableData();
};
</script>

<template>
  <!-- 使用 mx-auto 实现左右外边距自动，justify-center 让子元素水平居中 -->
  <div
    class="relative mx-auto flex items-center justify-center space-x-8"
    style="height: calc(100vh - 88px)"
  >
    <!-- 表单区域，隐藏时使用 v-show + transition -->
    <CollapsibleCard>
      <ElForm :model="submitForm" label-position="top" @keyup.enter="onSubmit">
        <ElFormItem :label="$t('views.common.collectDate')">
          <ElDatePicker
            v-model="submitForm.timeRange"
            type="daterange"
            date-format="yyyy-MM-DD"
            value-format="YYYY-MM-DD"
            unlink-panels
            range-separator="-"
            :start-placeholder="$t('views.common.startDate')"
            :end-placeholder="$t('views.common.endDate')"
            :shortcuts="shortcuts"
          />
        </ElFormItem>
        <ElFormItem :label="$t('views.common.supplier')">
          <ElSelect
            v-model="submitForm.supplier"
            multiple
            filterable
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.supplierOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.salesChannel')">
          <ElSelect
            v-model="submitForm.salesChannel"
            multiple
            filterable
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.salesChannelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="$t('views.common.salesType')">
          <ElSelect
            v-model="submitForm.salesType"
            :placeholder="$t('views.common.selectPlaceholder')"
          >
            <ElOption
              v-for="item in options.salesTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem>
          <div class="flex w-full justify-center">
            <ElButton type="primary" @click="onSubmit">
              {{ $t('views.common.filter') }}
            </ElButton>
            <ElButton>{{ $t('views.common.reset') }} </ElButton>
          </div>
        </ElFormItem>
      </ElForm>
    </CollapsibleCard>

    <ElCard class="relative !ml-1 h-full flex-1 !overflow-auto">
      <div
        class="hover:text-primary absolute right-6 top-4 z-10 cursor-pointer rounded-full bg-white p-1 text-gray-500 shadow-md transition-shadow hover:bg-gray-100 hover:shadow-lg dark:bg-neutral-800 dark:text-gray-300"
        @click="router.back()"
      >
        <StashArrowReply class="size-5" />
      </div>
      <div
        class="hover:text-primary absolute left-6 top-4 z-10 cursor-pointer rounded-full bg-white p-1 text-gray-500 shadow-md transition-shadow hover:bg-gray-100 hover:shadow-lg dark:bg-neutral-800 dark:text-gray-300"
        @click="router.back()"
      >
        <StashArrowReply class="size-5" />
      </div>
      <h2 class="my-2 flex items-center justify-center text-base font-bold">
        {{
          `${$t('views.report.salesDetails')}(${$t('views.report.company')})`
        }}
      </h2>
      <h2 class="tems-center mb-2 flex justify-center text-base font-bold">
        {{ submitForm.publisherName }}
      </h2>
      <div class="flex justify-end text-xs">
        <div class="mr-4">最后数据时间：{{ lastCollectDate }}</div>
        <div class="mr-4">
          {{ $t('views.common.statisticalDate') }}：<span
            v-if="submitForm.timeRange[0] && submitForm.timeRange[1]"
          >
            {{ `${submitForm.timeRange[0]}` }} -
            {{ `${submitForm.timeRange[1]}` }}
          </span>
        </div>
        <CurrentDateTime />
      </div>
      <ElTable
        :data="tableData"
        v-loading="searchLoading"
        border
        @sort-change="handleSortChange"
      >
        <ElTableColumn
          prop="serialNo"
          :label="$t('views.common.serialNo')"
          min-width="100"
          sortable="custom"
        />
        <ElTableColumn
          prop="bookName"
          :label="$t('views.common.bookName')"
          min-width="200"
          sortable="custom"
        />
        <ElTableColumn
          prop="barCode"
          :label="$t('views.common.ISBN')"
          min-width="120"
          sortable="custom"
        />
        <ElTableColumn
          prop="price"
          :label="$t('views.common.price')"
          align="right"
          sortable="custom"
        />
        <ElTableColumn
          prop="saleNum"
          :label="$t('views.common.totalVolumeNumber')"
          align="right"
          sortable="custom"
        />
        <ElTableColumn
          prop="saleMayang"
          :label="$t('views.common.totalFixedPrice')"
          align="right"
          sortable="custom"
        />
        <ElTableColumn
          prop="saleShiyang"
          :label="$t('views.common.totalSalePrice')"
          align="right"
          sortable="custom"
        />
        <ElTableColumn
          prop="saleDiscount"
          :label="$t('views.common.saleDiscount')"
          align="right"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer">
                  {{ $t('views.common.saleDiscount') }}
                </span>
                <template #content>
                  <div style="width: auto">总实洋/总码洋*100</div>
                </template>
              </ElTooltip>
            </span>
          </template>
        </ElTableColumn>
        <ElTableColumn
          prop="pubSettMoney"
          :label="$t('views.common.estimatedCost')"
          align="right"
          sortable="custom"
        />
        <ElTableColumn
          prop="expressMoney"
          :label="$t('views.common.expressDeliveryCost')"
          align="right"
          sortable="custom"
        />
        <ElTableColumn
          prop="platformMoney"
          :label="$t('views.common.platformDeductionPoints')"
          align="right"
          sortable="custom"
        />
        <ElTableColumn
          prop="saleSettlementProfit"
          :label="$t('views.common.saleSettlementProfit')"
          align="right"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer">
                  {{ $t('views.common.saleSettlementProfit') }}
                </span>
                <template #content>
                  <div style="width: auto">
                    实洋 - 预估成本 - 快递成本 - 平台扣点
                  </div>
                </template>
              </ElTooltip>
            </span>
          </template>
        </ElTableColumn>
        <ElTableColumn
          prop="settlementGrossProfitMargin"
          :label="$t('views.common.settlementGrossProfitMargin')"
          align="right"
          sortable="custom"
        >
          <template #header="scope">
            <span>
              <ElTooltip
                :aa="scope"
                class="item"
                effect="dark"
                placement="top-start"
              >
                <span class="cursor-pointer">
                  {{ $t('views.common.settlementGrossProfitMargin') }}
                </span>
                <template #content>
                  <div style="width: auto">毛利/销售实洋*100</div>
                </template>
              </ElTooltip>
            </span>
          </template>
        </ElTableColumn>
      </ElTable>
      <ElPagination
        :current-page="submitForm.pageNo"
        :page-size="submitForm.pageSize"
        :page-sizes="[20, 50, 100, 200]"
        class="mt-4 flex justify-end"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </ElCard>
  </div>
</template>

<style scoped>
:deep(.el-table .cell) {
  padding: 0 8px !important;
}
</style>
